Control structures are fundamental constructs in programming languages that allow you to control the flow of your code. They enable you to make decisions based on conditions, execute code repeatedly, and manage complex logic. In JavaScript, the most common control structures are conditional statements (if-else, switch), loops (for, while, do-while), and exception handling (try-catch-finally).
javascriptlet age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
javascriptlet grade = 85;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) {
console.log("B");
} else if (grade >= 70) {
console.log("C");
} else if (grade >= 60) {
console.log("D");
} else {
console.log("F");
}
javascriptlet age = 18;
let canVote = age >= 18 ? "Yes" : "No";
javascriptlet day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // "Wednesday"
javascriptfor (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
javascriptlet i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++;
}
javascriptlet i = 0;
do {
console.log(i); // 0, 1, 2, 3, 4
i++;
} while (i < 5);
javascriptlet array = [1, 2, 3, 4, 5];
for (let value of array) {
console.log(value); // 1, 2, 3, 4, 5
}
javascriptlet person = { name: "Alice", age: 30, city: "New York" };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
// "name: Alice", "age: 30", "city: New York"
}
try
block contains the code that might throw an exception. If an exception occurs, the catch
block is executed, allowing you to handle the error appropriately.javascripttry {
let result = 10 / 0; // Division by zero
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
}
finally
block is optional and contains code that is always executed, regardless of whether an exception occurs or not.javascripttry {
let result = 10 / 2;
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("This code will always run.");
}
Control structures are essential building blocks for creating complex programs and managing the flow of your code. By understanding and effectively using conditional statements, loops, and exception handling, you can create more robust and efficient JavaScript applications.